package com.daxia.bumall.web.controller.m;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.daxia.bumall.common.DecorateRequirementStatus;
import com.daxia.bumall.common.MyJSONObject;
import com.daxia.bumall.common.NeedLogin;
import com.daxia.bumall.common.Sex;
import com.daxia.bumall.common.UserType;
import com.daxia.bumall.dto.DecorateRequirementDTO;
import com.daxia.bumall.dto.DesignerDTO;
import com.daxia.bumall.exception.BizException;
import com.daxia.bumall.model.City;
import com.daxia.bumall.model.Designer;
import com.daxia.bumall.model.HouseStyle;
import com.daxia.bumall.model.HouseType;
import com.daxia.bumall.model.User;
import com.daxia.bumall.support.MPage;
import com.daxia.bumall.util.DateUtils;

@Controller
@RequestMapping(value = "/m/decorateRequirement", produces = "application/json;charset=UTF-8")
public class MDecorateRequirementController extends MBaseController {
	
	private static Logger logger = Logger.getLogger(MDecorateRequirementController.class);
    
	@NeedLogin
    @ResponseBody
    @RequestMapping("list")
    public String list(DecorateRequirementDTO dto, MPage page) throws Exception {
		User user = getCurrentUser();
		
    	MyJSONObject data = new MyJSONObject();
    	JSONArray decorateRequirementInfos = new JSONArray();
    	dto.setStatus(DecorateRequirementStatus.Init.getValue());
    	City city = user.getCity();
    	if (city != null) {
    		dto.setCityId(city.getId());
    	}
        List<DecorateRequirementDTO> decorateRequirementDTOs = decorateRequirementService.find(dto, page);
        for (DecorateRequirementDTO decorateRequirementDTO : decorateRequirementDTOs) {
        	MyJSONObject od = new MyJSONObject();
        	od.put("id", decorateRequirementDTO.getId());
        	od.put("username", decorateRequirementDTO.getUser().getUsername());
        	od.put("nickName", decorateRequirementDTO.getUser().getNickName());
        	od.put("mobile", decorateRequirementDTO.getUser().getMobile());
        	od.put("houseTypeImage", decorateRequirementDTO.getHouseTypeImage());
        	if (decorateRequirementDTO.getUser() != null &&  decorateRequirementDTO.getUser().getCity() != null) {
        		od.put("cityId", decorateRequirementDTO.getUser().getCity().getId());
        		od.put("cityName", decorateRequirementDTO.getUser().getCity().getName());
        	}
        	StringBuffer desc = new StringBuffer();
        	if (decorateRequirementDTO.getHouseType() != null) {
        		desc.append(decorateRequirementDTO.getHouseType().getName());
        	}
        	if (StringUtils.isNotBlank(decorateRequirementDTO.getArea())) {
        		desc.append("/" + decorateRequirementDTO.getArea() + "m²");
        	}
        	od.put("desc", desc.toString());
        	od.put("userHeadImage", decorateRequirementDTO.getUser().getHeadImage());
        	String houseStyle = "";
        	if (decorateRequirementDTO.getHouseStyle() != null) {
        		houseStyle = decorateRequirementDTO.getHouseStyle().getName();
        	}
        	od.put("desc", desc.toString());
        	od.put("userHeadImage", decorateRequirementDTO.getHouseTypeImage());
        	od.put("houseStyle", houseStyle);
        	decorateRequirementInfos.add(od);
        }
        data.put("decorateRequirementInfos", decorateRequirementInfos);
        data.put("total", decorateRequirementService.countAllOfADay().intValue());
        data.put("succeed", decorateRequirementService.countSuccedOfADay().intValue());
        super.setPageInfo(data, page);
        return toJson(data);
    }
    
    /**
     * 发布需求
     * @return
     * @throws IOException 
     */
    @NeedLogin
    @ResponseBody
    @RequestMapping("publish")
    public String publish(String description, String area, Long houseTypeId, Long houseStyleId, HttpServletRequest request) throws IOException {
    	User user = getCurrentUser();
    	
    	String image = saveFilesAndReturnFileName(request);
    	DecorateRequirementDTO dto = new DecorateRequirementDTO();
    	dto.setArea(area);
    	dto.setCreateTime(new Date());
    	dto.setDescription(description);
    	dto.setHouseStyle(new HouseStyle());
    	dto.getHouseStyle().setId(houseStyleId);
    	dto.setHouseType(new HouseType());
    	dto.getHouseType().setId(houseTypeId);
    	dto.setHouseTypeImage(image);
    	dto.setUser(user);
    	dto.setStatus(DecorateRequirementStatus.Init.getValue());
    	dto.setExpireTime(DateUtils.getOneMonthLater(new Date()));
    	decorateRequirementService.create(dto);
    	
    	return toJson("");
    }
    
    @NeedLogin
    @ResponseBody
    @RequestMapping("rush")
    public String rush(Long id) throws Exception {
    	logger.info("ID IS : " + id);
    	notNull(id, "ID IS NULL.");
    	User user = getCurrentUser();
    	
    	DesignerDTO designDTOQuery = new DesignerDTO();
    	User userQuery = new User();
    	userQuery.setId(user.getId());
    	designDTOQuery.setUser(userQuery);
		DesignerDTO designerDTO = designerService.findOne(designDTOQuery);
		
		if (designerDTO == null) {
			throw new BizException("此用户不是设计师用户");
		}
		
    	int i = decorateRequirementService.updateByIdAndDesignerId(id, designerDTO.getId());
    	if (i <= 0) {
    		throw new BizException("抢单失败！");
    	} 
    	return toJson();
    }
    
    @ResponseBody
    @RequestMapping("detail")
    public String detail(Long id) throws Exception {
    	logger.info("ID is : " + id);
    	notNull(id, "id can not be null.");
    	MyJSONObject data = new MyJSONObject();
    	MyJSONObject userInfo = new MyJSONObject();
    	DecorateRequirementDTO decorateRequirementDTO = decorateRequirementService.load(id);
    	userInfo.put("id", decorateRequirementDTO.getUser().getId());
    	userInfo.put("headImage", decorateRequirementDTO.getUser().getHeadImage());
    	userInfo.put("username", decorateRequirementDTO.getUser().getUsername());
    	userInfo.put("nickName", decorateRequirementDTO.getUser().getNickName());
    	userInfo.put("sex", decorateRequirementDTO.getUser().getSex());
    	userInfo.put("sexRemark", Sex.getByValue(decorateRequirementDTO.getUser().getSex()).getRemark());
    	String provinceName = "";
    	String cityName = "";
    	if (decorateRequirementDTO.getUser().getProvince() != null) {
    		provinceName = decorateRequirementDTO.getUser().getProvince().getName();
    	}
    	if (decorateRequirementDTO.getUser().getCity() != null) {
    		provinceName = decorateRequirementDTO.getUser().getCity().getName();
    	}
		userInfo.put("provinceName", provinceName);
		userInfo.put("cityName", cityName);
		userInfo.put("mobile", decorateRequirementDTO.getUser().getMobile());
    	
		String houseTypeName = "";
		String houseStyleName = "";
		if (decorateRequirementDTO.getHouseStyle() != null) {
			houseStyleName = decorateRequirementDTO.getHouseStyle().getName();
		}
		if (decorateRequirementDTO.getHouseType() != null) {
			houseTypeName = decorateRequirementDTO.getHouseType().getName();
		}
    	data.put("city", cityName);
    	data.put("communityName", "");
    	String area = "";
    	if (StringUtils.isNotBlank(decorateRequirementDTO.getArea())) {
    		area += decorateRequirementDTO.getArea() + "m²";
    	}
    	data.put("area", area);
    	data.put("houseTypeName", houseTypeName);
    	data.put("houseStyleName", houseStyleName);
    	data.put("houseImage", decorateRequirementDTO.getHouseTypeImage());
    	data.put("status", decorateRequirementDTO.getStatus());
    	data.put("statusRemark", DecorateRequirementStatus.getByValue(decorateRequirementDTO.getStatus()).getRemark());
    
    	data.put("userInfo", userInfo);
    	return toJson(data);
    }
    
    @NeedLogin
    @ResponseBody
    @RequestMapping("myDecorateRequirement")
    public String myDecorateRequirement(DecorateRequirementDTO decorateRequirementQuery, MPage page) throws Exception {
    	MyJSONObject data = new MyJSONObject();
    	JSONArray decorateRequirementInfos = new JSONArray();
    	User user = getCurrentUser();
    	if (user.getType().intValue() == UserType.Designer.getValue()) {
    		Designer designer = new Designer();
    		User designerUser = new User();
    		designerUser.setId(user.getId());
    		designer.setUser(designerUser);
    		String sort = " order by id desc ";
			decorateRequirementQuery.setSort(sort);
			decorateRequirementQuery.setDesigner(designer);
    	} else {
    		User normalUser = new User();
    		normalUser.setId(user.getId());
    		decorateRequirementQuery.setUser(user);
    		String sort = " order by status desc, id desc ";
			decorateRequirementQuery.setSort(sort );
    	}
    	List<DecorateRequirementDTO> decorateRequirementDTOList = decorateRequirementService.find(decorateRequirementQuery, page);
    	for (DecorateRequirementDTO dto : decorateRequirementDTOList) {
    		MyJSONObject od = new MyJSONObject();
        	od.put("id", dto.getId());
        	od.put("username", dto.getUser().getUsername());
        	od.put("nickName", dto.getUser().getNickName());
        	StringBuffer desc = new StringBuffer();
        	if (dto.getHouseType() != null) {
        		desc.append(dto.getHouseType().getName());
        	}
        	if (StringUtils.isNotBlank(dto.getArea())) {
        		desc.append("/" + dto.getArea() + "m²");
        	}
        	od.put("desc", desc.toString());
        	od.put("userHeadImage", dto.getUser().getHeadImage());
        	String houseStyle = "";
        	if (dto.getHouseStyle() != null) {
        		houseStyle = dto.getHouseStyle().getName();
        	}
        	od.put("houseStyle", houseStyle);
        	od.put("houseTypeImage", dto.getHouseTypeImage());
        	od.put("mobile", dto.getUser().getMobile());
        	od.put("status", dto.getStatus());
        	od.put("statusRemark", DecorateRequirementStatus.getByValue(dto.getStatus()).getRemark());
        	od.put("createTime", DateUtils.format(dto.getCreateTime(), "yyyy-MM-dd"));
        	od.put("expiredTime", DateUtils.format(dto.getExpireTime(), "yyyy-MM-dd"));
        	
        	if (dto.getDesigner() != null) {
        		MyJSONObject designerInfo = new MyJSONObject();
        		designerInfo.put("id", dto.getDesigner().getId());
        		designerInfo.put("mobile", dto.getDesigner().getUser().getMobile());
        		od.put("designerInfo", designerInfo);
        	}
        	
        	decorateRequirementInfos.add(od);
    	}
    	data.put("decorateRequirementInfos", decorateRequirementInfos);
    	return toJson(data);
    }
}
